#include <stdio.h>
#include <string.h>
#include <sys/time.h>
// #include <fcntl.h>
#include <sys/stat.h>
// #include <sys/types.h>
#include <unistd.h>
#include <dirent.h>
#include <stdlib.h>

#include "filefrag.h"

static int total_file = 0;
static unsigned long total_extent = 0; 
struct fiemap_extent* extents = NULL;
unsigned long long filesize = 0;
unsigned long long total_filesize = 0;

void fetchdir(char* path,void (*fcn)(char*))
{
    char name[256];
    struct dirent* stp;
    DIR* dp;

    // 打开目录
    if((dp = opendir(path))== NULL)
    {
        fprintf(stderr,"fetchdir error%s\n",path);
        return;
    }
    while((stp = readdir(dp)) != NULL)
    {
        if(strcmp(stp->d_name,".")==0 || strcmp(stp->d_name,"..")==0)
            continue;
        if(strlen(path)+strlen(stp->d_name)+2>sizeof(name))
        {
            fprintf(stderr,"fetchdir name %s %s too long\n",path,stp->d_name);
        }
        else
        {
            sprintf(name,"%s/%s",path,stp->d_name);
            fcn(name); //递归调用
        }
    }
    closedir(dp);

}
    

void isFile(char* path)
{
    struct stat sbuf;
    if(lstat(path,&sbuf)==-1)
    {
        fprintf(stderr,"lstat error%s\n",path);
    }
    
    // 判断是否是文件
    if((sbuf.st_mode & S_IFMT) == S_IFDIR)
    { 
        fetchdir(path,isFile);        
    }
    else{
        total_file++;
        extents = NULL;
        int extent = get_extent(path,&extents,&filesize);
        free(extents);
        total_extent += extent;
        total_filesize += filesize;

        printf("size:%ld extent:%d %s\n",sbuf.st_size,extent,path);   // 不是目录则是普通文件，直接打印文件名
    }

}

int main(int argc,char* argv[])
{
    if(argc == 1)
    {
        isFile(".");
    }
    else
    {
        isFile(argv[1]);
    }

    float average_fragment = total_extent/(float)total_file;
    unsigned long average_filesize = total_filesize/total_file;
    printf("total_file:%d\ntotal_extent:%lu\naverage fragment:%f\naverage filesize:%lu\n",total_file,total_extent,average_fragment,average_filesize);
    return 0;
}